# -*- coding: utf-8 -*-
import pickle
import redis
from urllib.parse import urlparse
from django.conf import settings


class RedisTools:
    def __init__(self):
        redis_url = settings.BROKER_URL
        parsed_url = urlparse(redis_url)
        db = parsed_url.path[1:]

        self.redis_host = parsed_url.hostname
        self.redis_port = parsed_url.port
        self.redis_password = parsed_url.password
        self.redis_db = int(db) if db else 5

        self.prefix = settings.IDC_REDIS_PREFIX
    
    def get_redis_pool(self):
        if self.redis_password:
            redis_pool = redis.ConnectionPool(
                host=self.redis_host, port=self.redis_port, password=self.redis_password, db=self.redis_db,
                max_connections=1000, retry_on_timeout=True)
        else:
            redis_pool = redis.ConnectionPool(
                host=self.redis_host, port=self.redis_port, db=self.redis_db,
                max_connections=1000, retry_on_timeout=True)
        redis_client = redis.Redis(connection_pool=redis_pool)
        return redis_client

    def get_redis_obj(self, key):
        r = self.get_redis_pool()
        value = r.get(f'{self.prefix}{key}')
        if value is not None:
            value = pickle.loads(value)
        return value

    def set_redis_obj(self, key, value, expiration_time=None):
        r = self.get_redis_pool()
        value = pickle.dumps(value)
        if expiration_time:
            r.set(f'{self.prefix}{key}', value, expiration_time)
        else:
            r.set(f'{self.prefix}{key}', value)
            
    def del_redis_obj(self, key):
        r = self.get_redis_pool()
        r.delete(f'{self.prefix}{key}')


redis_tool = RedisTools()
